<template>
  <div id="dict">
    <div class="tools">
      <el-form :model="search" label-width="40px" class="form-input-m" :inline="true">
        <el-form-item label="名称">
          <el-input type="text" v-model="search.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="键">
          <el-input type="text" v-model="search.key" placeholder="请输入键"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleSearch()">查询</el-button>
          <el-button @click="handleClear()">清空</el-button>
          <el-divider direction="vertical" />
          <el-button type="primary" @click="addDict">新建参数</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog title="参数信息" v-model="showDictDialog" :close-on-click-modal="false" :show-close="false" width="500px">
      <el-form ref="dictFormRef" :model="dictForm" :rules="dicFormRule" :inline-message="true" label-width="90px" class="form-input-m">
        <el-form-item prop="name" label="名称">
          <el-input type="text" v-model="dictForm.name" maxlength="50" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item prop="key" label="键">
          <el-input type="text" v-model="dictForm.key" maxlength="50" placeholder="请输入键"></el-input>
        </el-form-item>
        <el-form-item prop="value" label="值">
          <el-input type="text" v-model="dictForm.value" maxlength="50" placeholder="请输入值"></el-input>
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input type="text" v-model="dictForm.remark" maxlength="100" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="confirmDict(dictFormRef)">保 存</el-button>
        <el-button @click="closeDicDialog(dictFormRef)">取 消</el-button>
      </template>
    </el-dialog>
    <el-table v-loading="loading" row-key="id" :data="dictList" style="width: 100%" :height="conHeight">
      <el-table-column label="序号" width="60" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="150" align="center">
        <template #default="scope">
          <el-link type="primary" :underline="false" @click="editDict(scope.row, scope.$index)">{{ scope.row.dicName }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="dicKey" label="键" width="150" align="center"></el-table-column>
      <el-table-column prop="dicValue" label="值" width="200" align="center"></el-table-column>
      <el-table-column prop="remark" label="备注" align="center"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200" align="center"></el-table-column>
      <el-table-column label="操作" width="90" align="center">
        <template #default="scope">
          <el-button size="small" icon="EditPen" type="primary" plain circle @click="editDict(scope.row, scope.$index)"></el-button>
          <el-button size="small" type="danger" icon="Delete" plain circle @click="deleteDict(scope.row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="bottom-page">
      <el-pagination :background="true" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageIndex" :page-sizes="pageSizeList"
        :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalCount"></el-pagination>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance } from 'vue';
import type { FormInstance } from 'element-plus';
import { pageSizes, notifyType, notifyMessage } from '../../utils/common';
import { AppStore } from '../../stores/store';
let conHeight = ref(
  (document.documentElement.clientHeight || document.body.clientHeight) - 148 + 'px'
);
let { proxy }: any = getCurrentInstance();
let store = AppStore();
let pageSizeList = ref(pageSizes);
let pageSize = ref(pageSizes[0]);
let pageIndex = ref(1);
let totalCount = ref(0);
let loading = ref(false);
let showDictDialog = ref(false);
let dictFormRef = ref<FormInstance>();
let dictList: any = reactive([]);
// 添加参数表单
let dictForm = reactive({
  idx: 0, //当前在编辑的参数序号
  id: '',
  orgId: store.userInfo.orgId ? store.userInfo.orgId : null,
  name: '',
  key: '',
  value: '',
  remark: ''
});
// 查询键值表单
let search = reactive({
  name: '',
  key: ''
});
// 添加参数表单验证
let dicFormRule = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    }
  ],
  key: [
    {
      required: true,
      message: '请输入键',
      trigger: 'blur'
    },
    {
      validator: validateKey,
      trigger: 'blur'
    }
  ],
  value: [
    {
      required: true,
      message: '请输入值',
      trigger: 'blur'
    }
  ]
};

findDictionaryList();

// 获取参数列表的方法
function findDictionaryList() {
  loading.value = true;
  dictList.length = 0;
  const url = '/api/sys/findDictionaryList';
  proxy.$http
    .get(url, {
      params: {
        name: search.name,
        key: search.key,
        orgId: store.userInfo.orgId ? store.userInfo.orgId : 'admin',
        pageSize: pageSize.value,
        pageIndex: pageIndex.value
      }
    })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        dictList.push(...res.data.records);
        totalCount.value = res.data.total;
      }
      loading.value = false;
    })
    .catch((err: string) => {
      loading.value = false;
      notifyMessage(err, notifyType.warning, proxy);
    });
}
// 添加参数
function addDict() {
  showDictDialog.value = true;
}

// 添加参数时的校验
function validateKey(rule: any, value: any, callback: any) {
  const url = '/api/sys/findDictionaryByKey';
  proxy.$http
    .get(url, {
      params: {
        key: value,
        orgId: store.userInfo.orgId ? store.userInfo.orgId : 'admin'
      }
    })
    .then((res: any) => {
      if (res.data.dict) {
        if (!dictForm.id || res.data.dict.id !== dictForm.id) {
          callback(new Error('此键已存在，请重新添加'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    })
    .catch((err: string) => {
      callback(new Error(err));
    });
}

// 编辑参数
function editDict(row: any, $index: any) {
  dictForm.id = row.id;
  dictForm.name = row.name;
  dictForm.key = row.key;
  dictForm.value = row.value;
  dictForm.remark = row.remark;
  dictForm.idx = $index;
  showDictDialog.value = true;
}

// 保存参数
function confirmDict(formEl: any) {
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const postData = {
      id: dictForm.id,
      orgId: dictForm.orgId,
      dicName: dictForm.name,
      dicKey: dictForm.key,
      dicValue: dictForm.value,
      remark: dictForm.remark
    };
    // 判断添加和编辑
    let url = '';
    if (dictForm.id) {
      url = '/api/sys/editDictionary';
    } else {
      url = '/api/sys/addDictionary';
    }
    proxy.$http
      .post(url, postData)
      .then((res: any) => {
        if (res.status.code === 1) {
          notifyMessage('保存成功', notifyType.success, proxy);
          // 编辑保存
          if (dictForm.id) {
            dictList[dictForm.idx].name = dictForm.name;
            dictList[dictForm.idx].key = dictForm.key;
            dictList[dictForm.idx].value = dictForm.value;
            dictList[dictForm.idx].remark = dictForm.remark;
          } else {
            // 添加数据加载列表获取时间，数据量
            findDictionaryList();
          }
          showDictDialog.value = false;
          clearDictDialog();
        } else {
          notifyMessage(res.status.msg, notifyType.warning, proxy);
        }
      })
      .catch((err: string) => {
        notifyMessage(err, notifyType.warning, proxy);
      });
    return true;
  });
}
// 关闭添加参数弹框
function closeDicDialog(formRef: any) {
  showDictDialog.value = false;
  formRef.clearValidate();
  clearDictDialog();
}

// 清空弹框表单的方法
function clearDictDialog() {
  dictForm.id = '';
  dictForm.name = '';
  dictForm.key = '';
  dictForm.value = '';
  dictForm.remark = '';
  dictForm.idx = 0;
}
// 查询参数
function handleSearch() {
  pageIndex.value = 1;
  findDictionaryList();
}
// 清空查询框
function handleClear() {
  search.name = '';
  search.key = '';
}

//点击每页数量
function handleSizeChange(val: any) {
  pageSize.value = val;
  pageIndex.value = 1;
  findDictionaryList();
}

//点击跳转页码
function handleCurrentChange(val: any) {
  pageIndex.value = val;
  findDictionaryList();
}

// 删除参数
function deleteDict(id: any) {
  proxy
    .$confirm('确定删除此字典？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/sys/deleteDictionary';
      proxy.$http
        .post(url, { id })
        .then((res: any) => {
          if (res.status.code === 1) {
            notifyMessage('删除成功', notifyType.success, proxy);
            findDictionaryList();
          } else {
            notifyMessage(res.status.msg, notifyType.warning, proxy);
          }
        })
        .catch((err: string) => {
          notifyMessage(err, notifyType.warning, proxy);
        });
    })
    .catch((err: string) => {
      console.log(err);
    });
}
</script>
<style lang="scss" scoped>
.tools {
  .el-form-item--default {
    margin-bottom: 0 !important;
  }
}
</style>